package drds.binlog.parse.driver.utils;

import org.apache.commons.lang.ArrayUtils;

import java.io.IOException;

public class LengthCodedStringReader
{

    public static final String UTF_8 = "UTF-8";


    private int startIndex = 0;      // 数组下标
    private String encoding;

    public LengthCodedStringReader(int startIndex, String encoding)
    {

        this.startIndex = startIndex;
        this.encoding = encoding;
    }

    public String readLengthCodedString(byte[] bytes) throws IOException
    {
        long length = Bytes.readLength(bytes, getStartIndex());//具体的长度
        if (Bytes.null_object_length == length)
        {
            return null;
        }
        byte[] lengthBytes = Bytes.readLengthBytes(bytes, getStartIndex());//对应的字节
        setStartIndex(getStartIndex() + lengthBytes.length);//略过只是字节的地方
        try
        {
            return new String(ArrayUtils.subarray(bytes, getStartIndex(), (int) (getStartIndex() + length))//
                    , encoding == null ? UTF_8 : encoding);//
        } finally
        {
            setStartIndex((int) (getStartIndex() + length));
        }

    }

    public int getStartIndex()
    {
        return startIndex;
    }

    public void setStartIndex(int startIndex)
    {
        this.startIndex = startIndex;
    }
}
